import {
  getToken,
  removeToken
} from '@/utils/jsCookie'
import { Session } from '@/utils/storage'
import { buildMenus } from '@/api/system/menu'

const state = {
  token: getToken(),
  userInfo: Session.get('userInfo') || {
    userName: ''
  },
  roles: [],
  rolesBtnMenu: ''
}

const mutations = {
  // 设置用户信息
  SET_USER_INFO(state, data) {
    state.userInfo = data
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROLES_BTN_MENU: (state, roles) => {
    state.rolesBtnMenu = roles
  }
}

const actions = {
  // 设置用户信息
  async setUserInfos({ commit }, data) {
    if (data) {
      commit('SET_USER_INFO', data)
    } else {
      if (Session.get('userInfo')) commit('SET_USER_INFO', Session.get('userInfo'))
    }
  },
  // get roles
  getRoles({ commit, state }) {
    return new Promise((resolve, reject) => {
      buildMenus(state.token)
        .then(({ list }) => {
          if (!list) {
            reject('登录失效，请重新登录。')
          }
          const rolesArry = []
          const rolesMenuArray = []
          list.forEach(el => {
            if (!el.hidden) rolesArry.push(el.path)
            if (el.children && el.children.length) {
              el.children.forEach(v => {
                if (!v.hidden) rolesArry.push(v.path)
                if (v.children && v.children.length > 0) {
                  v.children.forEach(m => {
                    if (!m.hidden) {
                      rolesArry.push(m.permission)
                      rolesMenuArray.push(m.permission)
                    }
                  })
                }
              })
            }
          })
          commit('SET_ROLES', rolesArry)
          commit('SET_ROLES_BTN_MENU', rolesMenuArray)
          if (!list || list.length <= 0) {
            reject('该账号当前无任何权限，请联系管理员。')
          }
          resolve({ roles: rolesArry })
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // user login
  login({ commit }, userInfo) {
    commit('SET_USER_INFO', userInfo)
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_ROLES_BTN_MENU', [])
      removeToken()
      resolve()
    })
  }
}

const userInfosModule = {
  namespaced: true,
  state,
  mutations,
  actions
}

export default userInfosModule
